package net;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;


import com.aliang.auto.R;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.http.app.RedirectHandler;
import org.xutils.http.request.UriRequest;
import org.xutils.x;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.sql.ClientInfoStatus;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;

import app.auto.AndroidInstance;
import app.auto.runner.base.DipUtil;
import app.auto.runner.base.Prt;
import app.auto.runner.base.framework.CrashHandler;
import app.auto.runner.base.framework.Init;
import app.auto.runner.base.intf.FunCallback;
import app.auto.runner.base.intf.MapBuilder;
import app.auto.runner.base.utility.BackStack;
import app.auto.runner.base.utility.FillUtil;
import app.auto.runner.base.utility.HandlerUtil;
import app.auto.runner.base.utility.ShareAlert;

/**
 * Desc:请求检索工具
 * <p>
 * Author: AnYaBo
 * Date: 2020/4/17
 * Copyright: Copyright (c) 2016-2022
 * Company: @小牛科技
 * Email:anyabo@xiaoniu.com
 * Update Comments:
 *
 * @author anyabo
 */
public class BaiduNetUtil extends AndroidInstance {
    private static final String TAG = "RequestRetrievalUtils";
    private static final String USER_AGENT = "User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36";

    public void fetch(final String searchWord, int pageno, final FunCallback picArrayCallBack) {
        try {
            RequestParams requestParams = new RequestParams("https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=index&fr=&hs=0&xthttps=111111&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8++&rsp=-1&word=" + searchWord + "&oq=" + searchWord);
//            requestParams.addQueryStringParameter("latest", "0");
            requestParams.addQueryStringParameter("z", "4");
            requestParams.addQueryStringParameter("pn", pageno + "");


            requestParams.setHeader("User-Agent", USER_AGENT);
            x.http().get(requestParams, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
//                    try {

                    Prt prt = Prt.cat("\"thumbURL\":\"", ".jpg", result);
                    if (prt == null) {
                        return;
                    }
                    Set<String> list = new TreeSet<String>();
                    list.add(prt.getPrt() + ".jpg");
                    String part = result;

                    while (part.contains("thumb")) {
                        try {
                            prt = Prt.cat("\"thumbURL\":\"", ".jpg", 0, part);
                            if (prt == null || prt.getPrt() == null) {
                                break;
                            }

                            part = part.substring(prt.getBoundafteridx());
                            if (prt.getPrt().startsWith("http") && !list.contains(prt.getPrt() + ".jpg")) {
                                list.add(prt.getPrt() + ".jpg");
                            }
                        } catch (Exception e) {
//                            CrashHandler.errorDialog(e);
                        }

                    }

//
//
//                        JSONObject jsonBody = new JSONObject(result);
//                        JSONArray dataArray = jsonBody.getJSONArray("data");
//                        List<String> imgUrlList = new ArrayList<>();
//                        for (int i = 0; i < dataArray.length(); i++) {
//                            try {
//                                JSONObject dataObject = dataArray.getJSONObject(i);
//                                String imgUrl = dataObject.getString("objURL");
//                                imgUrlList.add(imgUrl);
//                            } catch (Exception e) {
//                            }
//                        }
                    if (picArrayCallBack != null) {
                        picArrayCallBack.onCallback(new ArrayList<String>(list),null);
                    }
//                    } catch (JSONException e) {
//                        if (picArrayCallBack != null) {
//                            picArrayCallBack.callback(new ArrayList<String>());
//                        }
//                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    Log.e(TAG, ex.toString());
                    if (picArrayCallBack != null) {
                        picArrayCallBack.onCallback(new ArrayList<String>(),null);
                    }
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
            if (picArrayCallBack != null) {
                picArrayCallBack.onCallback(new ArrayList<String>(),null);
            }
        }
    }


    @Override
    public AndroidInstance use(Object mp, Object... p) {
        ListView lv;
        BaiduNetUtil.get(BaiduNetUtil.class,getContext()).fetch("月光族", 1, new FunCallback() {

            @Override
            public void onCallback(Object result, final Object o) {
                super.onCallback(result, o);
            }
        });
        return null;
    }
//                List ls = ExtractUtil.get(ExtractUtil.class, context).outputListFields((List<Object>) result, String.class, "title");
//                List imgls = ExtractUtil.get(ExtractUtil.class, context).outputListFields((List<Object>) result, String.class, "source-icon");
//                List href = ExtractUtil.get(ExtractUtil.class, context).outputListFields((List<Object>) result, String.class, "href");
//                List id = ExtractUtil.get(ExtractUtil.class, context).outputListFields((List<Object>) result, String.class, "id");
//                final List out = ExtractUtil.get(ExtractUtil.class, context).combine(imgls, ls, href, id);
//                FillUtil.get(FillUtil.class, getContext())
//                        .setImageField("source-icon").setTextField("title").setUrlTransfer(new FunCallback() {
//                    @Override
//                    public void simpleRun(Object aty, Object... p) {
//                        super.simpleRun(aty, p);
//                        try {
//                            setResult((String) aty);
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }).fillList(lv, (List) result, new FunCallback() {
//                    @Override
//                    public void onCallback(Object result, Object object) {
//                        super.onCallback(result, object);
//
//                        search(lv, searchword, 20);
//                    }
//                }, new FunCallback() {
//                    @SuppressLint("NewApi")
//                    @Override
//
//                    public void onCallback(Object result, Object object) {
//                        super.onCallback(result, object);
//                        AdapterView adapterView = (AdapterView) result;
//                        int pos = (int) object;
//                        Object item = adapterView.getItemAtPosition(pos);
//                        String data = "";
//                        String go = "";
//                        if (item instanceof Map) {
//                            data = (String) ((Map) item).get("href");
//                            go = data;
//                        }
//                        final View progressview = LayoutInflater.from(context).inflate(com.manban.style.R.layout.layout_mi_loading_text, null);
//                        final ProgressBar progressBar = (ProgressBar) progressview.findViewById(R.id.loading);
//
////                        ToastUtil.live((Activity) getContext()).toast(go);
//                        RelativeLayout frameLayout;
//                        View web = LayoutInflater.from(getContext()).inflate(R.layout.activity_web, null);
//                        frameLayout = ((RelativeLayout) web.findViewById(R.id.webView));
//
//                        pop = PopUtil.get(PopUtil.class, getContext()).popWindow((Activity) getContext(), web);
//                        String finalGo = go;
//                        web.findViewById(R.id.btn_share).setOnClickListener(new OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                ShareUtil.get(ShareUtil.class, v.getContext()).shareMsg("1", "2", finalGo, "");
//                            }
//                        });
//                        web.findViewById(R.id.btn_back).setOnClickListener(new OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                pop.dismiss();
//                                pop = null;
//                            }
//                        });
//
//                        AgentWeb.PreAgentWeb agentWeb = AgentWeb.with((Activity) getContext())//这里需要把 Activity 、 和 Fragment  同时传入
//                                .setAgentWebParent(frameLayout, new RelativeLayout.LayoutParams(-1, -1))// 设置 AgentWeb 的父控件 ， 这里的view 是 LinearLayout ， 那么需要传入 LinearLayout.LayoutParams
//                                .useDefaultIndicator()// 使用默认进度条
//                                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK) //注意这里开启 strict 模式 ， 设备低于 4.2 情况下回把注入的 Js 全部清空掉 ， 这里推荐使用 onJsPrompt 通信
//                                .setWebViewClient(new WebViewClient() {
//                                    List urls = new ArrayList();
//
//                                    @Override
//                                    public void onLoadResource(WebView view, String url) {
//                                        super.onLoadResource(view, url);
//                                        if (url.contains(".js")) {
//                                            return;
//                                        }
//                                        x.image().loadDrawable(url, null, new Callback.CommonCallback<Drawable>() {
//                                            @Override
//                                            public void onSuccess(Drawable result) {
//                                                urls.add(url);
//                                            }
//
//                                            @Override
//                                            public void onError(Throwable ex, boolean isOnCallback) {
//
//                                            }
//
//                                            @Override
//                                            public void onCancelled(CancelledException cex) {
//
//                                            }
//
//                                            @Override
//                                            public void onFinished() {
//
//                                            }
//                                        });
//                                    }
//
//                                    @Override
//                                    public void onPageFinished(WebView view, String url) {
//                                        super.onPageFinished(view, url);
//                                        TrtUtil.trt(url, view);
//
//                                        ShareAlert.shareAlert((Activity) getContext(), urls.toString());
//                                    }
//                                })
//                                .createAgentWeb().ready();//
//
//                        RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(DipUtil.fromDip(90), DipUtil.fromDip(90));
//                        rl.addRule(RelativeLayout.CENTER_IN_PARENT);
//                        frameLayout.addView(progressview, rl);
//
//                        agentWeb.go(go);
//
//                        BackStack.map((Activity) getContext()).onClickRun(new FunCallback() {
//                            @Override
//                            public void onCallback(Object result, Object object) {
//                                super.onCallback(result, object);
//                                if (pop != null) {
//                                    pop.dismiss();
//                                }
//                                pop = null;
//                            }
//                        });
//                    }
//                });




        public static class EntityObj {
            public Map map = new TreeMap();

            public Map getMap() {
                return map;
            }

            public String[] k;

            public EntityObj initKeys(String... k) {
                this.k = k;

                return this;
            }

            public EntityObj initValues(Object... v) {

                if (v != null && k != null && k.length == v.length) {
                    for (int i = 0; i < k.length; i++) {
                        getMap().put(k[i], v[i]);
                    }
                } else {
                    throw new RuntimeException("mismatch inited values' length to keys' length");
                }
                return this;
            }


            public EntityObj putValue(String k, Object v) {
                getMap().put(k, v);
                return this;
            }

            public Object getValue(String k) {
                return getMap().get(k);
            }
        }

        public static class EntityVideo extends EntityObj {

            public static final String VIDEO_URL = "VIDEO_URL";
            public static final String VIDEO_TITLE = "VIDEO_TITLE";
            public static final String VIDEO_AUTHOR = "VIDEO_AUTHOR";
            public static final String VIDEO_COVER_URL = "VIDEO_COVER_URL";
            public static final String VIDEO_DURATION = "VIDEO_DURATION";
            public static final String VIDEO_PUBLISH_TIME_TEXT = "VIDEO_PUBLISH_TIME_TEXT";

        }
    }
